package com.aispeech.asr.clib.arpc;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import com.sun.jna.Pointer;

import lombok.extern.slf4j.Slf4j;


@Slf4j
@Deprecated
public class IntranetCallBack implements IARpcCallback {
	
    private CountDownLatch startDownLatch = new CountDownLatch(1);
    private CountDownLatch eofDownLatch = new CountDownLatch(1);
    private boolean started = false;
    
    private int state = -1;
    private Pointer data;
    private int size; 
    private Pointer userData;
    
    private IARpcCallback callback;
    
    public IntranetCallBack(IARpcCallback callback) {
    	this.callback = callback;
    }
	
	public void callback(String sessionid, int state, Pointer data, int size, Pointer userData) {
		
		this.state = state;
		this.data = data;
		this.size = size;
		this.userData = userData;
		
		if (started) {
			//onFeed(sessionid, state, data, size, userData);
			callback.callback(sessionid, state, data, size, userData);
		}
		
		if(startDownLatch != null && startDownLatch.getCount() == 1) {
			startDownLatch.countDown();
		}
		if(eofDownLatch != null && eofDownLatch.getCount() == 1 && state != EARpcState.S_OK.getValue()) {
			eofDownLatch.countDown();
		}

	}

	
	public int onStart() {
		log.info("[ IntranetCallBack.onStart ] started: {}", started);
		try {
			startDownLatch.await(5,TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			log.error("IntranetCallBack error", e);
		}
		
		started = true;
		byte[] bytes = data == null ? new byte[0] : data.getByteArray(0, size);
		String errorMsg = String.format("[ IntranetCallBack.onStart ] state: %d, reason: %s", state, new String(bytes, StandardCharsets.UTF_8));
		
		log.info("[ IntranetCallBack.onStart ] started: {},state:{}", started,state);
		return state;
	}
	
	public int onStop() {
		log.info("[ IntranetCallBack.onStop ] started");
		try {
			eofDownLatch.await(1,TimeUnit.MINUTES);
		} catch (InterruptedException e) {
			log.error("IntranetCallBack error", e);
		}
		
		byte[] bytes = data == null ? new byte[0] : data.getByteArray(0, size);
		String errorMsg = String.format("[ IntranetCallBack.onStop ] state: %d, reason: %s", state, new String(bytes, StandardCharsets.UTF_8));
		
		log.info("[ IntranetCallBack.onStop ] state:{}", started,state);
		return state;
	}

}
